package org.tony.spider.common;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.tony.spider.common.Browser.RequestType;

public class Address
{
  private String              url;
  private String              host;
  private Map<String, Object> params;
  private RequestType         requestType;
  private String              urlEncoding;

  public Address(String url)
  {
    this.url = url;
    this.requestType = RequestType.get;
    this.urlEncoding = "GB2312";
    this.params = new HashMap<String, Object>();
    try
    {
      this.host = new URL(url).getHost();
    }
    catch (MalformedURLException e)
    {
      this.host = null;
    }
  }

  public Address(String url, RequestType req)
  {
    this(url);
    this.requestType = req;
  }

  public Address(String url, RequestType req, Map<String, Object> params)
  {
    this(url, req);
    this.params = params;
  }

  public String getUrl()
  {
    return url;
  }

  public void setUrl(String url)
  {
    this.url = url;
  }

  public Map<String, Object> getParams()
  {
    return params;
  }

  public void setParams(Map<String, Object> params)
  {
    this.params = params;
  }

  public RequestType getRequestType()
  {
    return requestType;
  }

  public void setRequestType(RequestType requestType)
  {
    this.requestType = requestType;
  }

  public String getHost()
  {
    return host;
  }

  public String getUrlEncoding()
  {
    return urlEncoding;
  }

  public void setUrlEncoding(String urlEncoding)
  {
    this.urlEncoding = urlEncoding;
  }

  public String buildUrl()
  {
    StringBuilder urlBuilder = new StringBuilder(url);
    if (requestType == RequestType.get)
    {
      String prefix = "";
      String regex = "(.+)(\\?.+)";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(this.url);
      if (m.find())
      {
        prefix = "&";
      }
      else
      {
        prefix = "?";
      }
      urlBuilder.append(prefix);
      for (Iterator<String> iter = params.keySet().iterator(); iter.hasNext();)
      {
        String key = iter.next();
        try
        {
          urlBuilder.append(String.format("%s=%s", key,
              URLEncoder.encode(params.get(key).toString(), urlEncoding)));
        }
        catch (UnsupportedEncodingException e)
        {
          e.printStackTrace();
        }
        if (iter.hasNext())
        {
          urlBuilder.append("&");
        }
      }
    }
    return urlBuilder.toString();
  }
}
